export const paramTypeReg = {
  LETTER:/^[A-Za-z]*$/,
  NUM:/^[0-9]*$/,
  INTEGER:/^[1-9][0-9]*$/,
  STRING:/^\w+$/,
  EMAIL: /^[\w-]+@[\w-]+\.[\w\.-]*\w$/,
  USERNAME_DEFAULT: /^[A-Za-z]\w{5,15}$/,                     /*字母开头，6-16位*/
  PASSWORD_DEFAULT: /(?!^[0-9]+$)(?!^[A-Za-z]+$)^.{6,16}$/   /*不能是单独的数字或字母，6-10位*/
}

function check(tocheck, by){
  var finalkey = "";
  Object.keys(by).map(key=>{
    //console.log(key, tocheck[key], by[key]);
    if ((!tocheck[key]) || (!by[key].test(tocheck[key]))){
      finalkey = key; 
    }
  });
  return finalkey;
}

export function checkParam(by){
  return async function(ctx, next){
    var key = check(ctx.params, by);

    if (key){
      ctx.throw(301, key + " ERROR IN PARAM");
    }
    return next();
  }
}

export function checkBody(by){
  return async function(ctx, next){
   
    if (ctx.request.method !== 'GET' && (!ctx.request.body)){
      ctx.throw(301, "user koa-body to parse requerst body first");
    }

    var tocheck = ctx.request.method === 'GET' ? ctx.request.query:ctx.request.body;
    var key = check(tocheck, by);

    if (key){
      ctx.throw(301, ctx.request.method === 'GET'?(key + " ERROR IN QUERY"):(key + " ERROR IN BODY"));
    }
    return next();
  }
}